package top.fyxxxx.dbdesign.servlet;

import top.fyxxxx.dbdesign.dao.DBoperate;
import top.fyxxxx.dbdesign.data.Account;
import top.fyxxxx.dbdesign.util.LoginModule;
import top.fyxxxx.dbdesign.util.SysUtil;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashSet;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet implements LoginModule {
    private DBoperate dBoperate=DBoperate.getInstance();
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        String action=request.getParameter("action");
        if (action.equals("login")) {
            dealLogin(request,response);
        } else if (action.equals("register")) {
            dealRegister(request,response);
        }else if(action.equals("logout")) {
            dealLogout(request);
        }
    }

    private void dealLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session=request.getSession(false);
        String account,pwd,captcha,check,error=null;
        account=request.getParameter("Account");
        pwd=request.getParameter("Password");
        captcha=request.getParameter("CAPTCHA");
        check=session==null?null:(String)session.getAttribute("CheckCode");
        if(SysUtil.hasNull(account,pwd,captcha,check)){//参数错误
            request.setAttribute("message","Incomplete parameters!");
        } else if(!captcha.equalsIgnoreCase(check)){//验证码错误
            request.setAttribute("verifyerror","Incorrect CAPTCHA!");
        } else {//尝试登陆
            long uid=login(account,pwd);
            if(uid==-1)//账号不存在或密码错误
                request.setAttribute("error","Bad password or account does not exist.");
            else {
                success(request, response, uid);//成功
                return;
            }
        }
        //     out.print("<script>alert('"+error+"'); window.location='index.jsp' </script>");
        request.getRequestDispatcher("/index.jsp").forward(request,response);
    }
    private void dealRegister(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        HttpSession session=request.getSession(false);
        String account,pwd,captcha,check,power,error=null;
        account=request.getParameter("Account");
        pwd=request.getParameter("Password");
        captcha=request.getParameter("CAPTCHA");
        power=request.getParameter("Power");
        check=session==null?null:(String)session.getAttribute("CheckCode");
        synchronized (this) {
            if (SysUtil.hasNull(account, pwd, captcha, check,power)){
                request.setAttribute("message","Incomplete parameters!");
            } else if (!captcha.equalsIgnoreCase(check)){
                request.setAttribute("verifyerror","Incorrect CAPTCHA!");
            } else {
                try {
                    if (register(account,pwd,Long.parseLong(power))){
                        //注册成功
                        request.getRequestDispatcher("./index.jsp").forward(request,response);
                        return;
                    }else request.setAttribute("error","The account is already taken.");
                } catch (Exception e) {
                    e.printStackTrace();
                    request.setAttribute("message","Database error.");
                }
            }
            request.getRequestDispatcher("/register.jsp").forward(request,response);
        }
    }
    private void dealLogout(HttpServletRequest request){
        request.getSession().removeAttribute("uid");
    }
    private void success(HttpServletRequest request, HttpServletResponse response,long uid){
        HttpSession session=request.getSession();
        session.removeAttribute("CheckCode");
        session.setAttribute("uid",uid);
        try {
            Account acc=dBoperate.getAccountByUid(uid);
            if(acc.getPower()==0)request.getRequestDispatcher("/studentMainPage.jsp").forward(request,response);
            else request.getRequestDispatcher("/teacherMainPage.jsp").forward(request,response);
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public long login(String acc, String pwd) {
        Account ac= dBoperate.getAccountByaccount(acc);
        if(ac.getUid()!=-1&&pwd.equals(ac.getPassword()))return ac.getUid();
        return -1;
    }

    @Override
    public boolean register(String acc, String pwd,long power) {
        long time= System.currentTimeMillis();
        Account ac=new Account(acc,pwd,acc,time,time,power,new HashSet<Long>());
        return dBoperate.insertAccount(ac)==1;
    }
}
